namespace Stee.CAP8.MessageBus.Sagas.Order
{
    using Stee.CAP8.MessageBus.Interface.Models;
    using Stee.CAP8.MessageBus.Sagas.Order.Sagas;
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    using Stee.CAP8.MessageBus.Sagas.Order.Sagas.Data;
    using Stee.CAP8.MessageBus.Sagas.Core.Handler;
    using Stee.CAP8.MessageBus.Sagas.Core.Sagas.Storages.Steps;
    using Stee.CAP8.MessageBus.Sagas.Core.Sagas.Storages.Nodes;
    using Stee.CAP8.MessageBus.Sagas.Core.Common;

    public class HandleMessages : IHandleMessage<CommandMessage>
    {
        private readonly IServiceProvider serviceProvider;
        private readonly ISagaNodeStorage sagaNodeStorage;

        private readonly List<string> orderActions = new List<string> { "PaymentSub.Payment", "StockSub.StockAdjust" };
        public HandleMessages(IServiceProvider serviceProvider, ISagaNodeStorage sagaNodeStorage)
        {
            this.serviceProvider = serviceProvider;
            this.sagaNodeStorage = sagaNodeStorage;
        }
        //这里写当你收到了自己订阅的消息以后怎么办，
        //调用哪个saga类的哪个方法
        public async Task Handle(CommandMessage message)
        {
            var actionName = message.Action;
            //处理OrderSagaMain
            if (this.orderActions.Contains(actionName)) //{ "PaymentSub.Payment", "StockSub.StockAdjust" };
            {

                try
                {
                    var sagaHandler = this.serviceProvider.GetService<OrderSagaMain>();

                    ///TODO 分析此message中是否有excetion有，则rollback
                    ////if(HasException)
                    //{

                    //    await sagaHandler.Rollback();

                    //}
                    var sagaData = new OrderSagaData(message.CorrelationID);
                    //在这里就标记为已成功？
                    this.sagaNodeStorage.Insert(new SagaNodeData
                    {
                        CommandMessageData = message.ObjToBytes(),
                        Id = Guid.NewGuid(),
                        IsDeleted = false,
                        RecordId = message.RecordID,
                        SagaId = message.CorrelationID,
                        SagaNodeStatus = Core.Sagas.Storages.Enums.SagaNodeState.SUCCESS,
                        TimeStamp = DateTime.Now
                    });
                    sagaHandler.SetSagaData(sagaData);
                    await sagaHandler.HandleReply(message).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw ex;
                }

            }


        }


    }


}
